package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.dto.ParamDefinitionDTO;
import com.zhentao.dto.ParamDefinitionQueryDTO;
import com.zhentao.mapper.ParamDefinitionMapper;
import com.zhentao.pojo.ParamDefinition;
import com.zhentao.service.ParamDefinitionService;
import com.zhentao.vo.ParamDefinitionVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author hp
* @description 针对表【param_definition(参数定义表：定义参数的基本属性和规则)】的数据库操作Service实现
* @createDate 2025-08-28 08:36:25
*/
@Service
public class ParamDefinitionServiceImpl extends ServiceImpl<ParamDefinitionMapper, ParamDefinition>
    implements ParamDefinitionService{

    @Override
    public Page<ParamDefinitionVO> queryParamDefinitions(ParamDefinitionQueryDTO queryDTO) {
        // 构建查询条件
        LambdaQueryWrapper<ParamDefinition> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(queryDTO.getParamKey()), ParamDefinition::getParamKey, queryDTO.getParamKey())
                   .like(StringUtils.hasText(queryDTO.getParamName()), ParamDefinition::getParamName, queryDTO.getParamName())
                   .eq(queryDTO.getCategoryId() != null, ParamDefinition::getCategoryId, queryDTO.getCategoryId())
                   .eq(StringUtils.hasText(queryDTO.getDataType()), ParamDefinition::getDataType, queryDTO.getDataType())
                   .eq(queryDTO.getIsRequired() != null, ParamDefinition::getIsRequired, queryDTO.getIsRequired())
                   .eq(queryDTO.getIsSystem() != null, ParamDefinition::getIsSystem, queryDTO.getIsSystem())
                   .like(StringUtils.hasText(queryDTO.getTags()), ParamDefinition::getTags, queryDTO.getTags())
                   .orderByDesc(ParamDefinition::getCreateTime);
        
        // 分页查询
        Page<ParamDefinition> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        Page<ParamDefinition> resultPage = this.page(page, queryWrapper);
        
        // 转换为VO
        Page<ParamDefinitionVO> voPage = new Page<>();
        BeanUtils.copyProperties(resultPage, voPage);
        
        List<ParamDefinitionVO> voList = resultPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        voPage.setRecords(voList);
        
        return voPage;
    }

    @Override
    public ParamDefinitionVO getParamDefinitionDetail(Long id) {
        ParamDefinition paramDefinition = this.getById(id);
        if (paramDefinition == null) {
            return null;
        }
        return convertToVO(paramDefinition);
    }

    @Override
    public boolean createParamDefinition(ParamDefinitionDTO dto) {
        // 检查参数键是否已存在
        if (existsByParamKey(dto.getParamKey(), null)) {
            throw new RuntimeException("参数键已存在：" + dto.getParamKey());
        }
        
        ParamDefinition paramDefinition = new ParamDefinition();
        BeanUtils.copyProperties(dto, paramDefinition);
        // 为空字符串的可选字段置为 null，避免写入 JSON/TEXT 列出错
        if (!StringUtils.hasText(paramDefinition.getValueRange())) {
            paramDefinition.setValueRange(null);
        }
        if (!StringUtils.hasText(paramDefinition.getValidationRule())) {
            paramDefinition.setValidationRule(null);
        }
        if (!StringUtils.hasText(paramDefinition.getTags())) {
            paramDefinition.setTags(null);
        }
        paramDefinition.setCreateTime(new Date());
        paramDefinition.setCreateBy("system"); // 实际应该从当前用户上下文获取
        
        return this.save(paramDefinition);
    }

    @Override
    public boolean updateParamDefinition(Long id, ParamDefinitionDTO dto) {
        ParamDefinition existParam = this.getById(id);
        if (existParam == null) {
            throw new RuntimeException("参数定义不存在");
        }
        
        // 检查参数键是否已存在（排除当前记录）
        if (existsByParamKey(dto.getParamKey(), id)) {
            throw new RuntimeException("参数键已存在：" + dto.getParamKey());
        }
        
        BeanUtils.copyProperties(dto, existParam);
        if (!StringUtils.hasText(existParam.getValueRange())) {
            existParam.setValueRange(null);
        }
        if (!StringUtils.hasText(existParam.getValidationRule())) {
            existParam.setValidationRule(null);
        }
        if (!StringUtils.hasText(existParam.getTags())) {
            existParam.setTags(null);
        }
        existParam.setUpdateTime(new Date());
        existParam.setUpdateBy("system"); // 实际应该从当前用户上下文获取
        
        return this.updateById(existParam);
    }

    @Override
    public boolean deleteParamDefinition(Long id) {
        ParamDefinition existParam = this.getById(id);
        if (existParam == null) {
            throw new RuntimeException("参数定义不存在");
        }
        
        // 系统参数不允许删除
        if (existParam.getIsSystem() != null && existParam.getIsSystem() == 1) {
            throw new RuntimeException("系统参数不允许删除");
        }
        
        return this.removeById(id);
    }

    @Override
    public boolean existsByParamKey(String paramKey, Long excludeId) {
        LambdaQueryWrapper<ParamDefinition> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ParamDefinition::getParamKey, paramKey);
        if (excludeId != null) {
            queryWrapper.ne(ParamDefinition::getId, excludeId);
        }
        return this.count(queryWrapper) > 0;
    }
    
    /**
     * 将实体转换为VO
     */
    private ParamDefinitionVO convertToVO(ParamDefinition entity) {
        ParamDefinitionVO vo = new ParamDefinitionVO();
        BeanUtils.copyProperties(entity, vo);
        
        // 可以在这里添加关联查询，如分类名称等
        // if (entity.getCategoryId() != null) {
        //     ParamCategory category = paramCategoryService.getById(entity.getCategoryId());
        //     if (category != null) {
        //         vo.setCategoryName(category.getCategoryName());
        //     }
        // }
        
        return vo;
    }
}




